#include "client.h"
#include "ui_client.h"

Client::Client(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Client)
{
    ui->setupUi(this);
    /* create udp socket object */
    this->udp = new QUdpSocket(this);

    /* 设置要发送消息的ip and port */
    ui->serverIp->setText("127.0.0.1");
    ui->serverPort->setText("8888");

    /* bind self port */
    ui->clientPort->setText("9999");
    this->udp->bind(ui->clientPort->text().toInt());

    /* send msg to client when send button is pressed*/
    connect(ui->send, &QPushButton::clicked, this, [=](){
        QString str = ui->sendBuffer->toPlainText();
        if (str.length()) {
            this->udp->writeDatagram(str.toUtf8(),
                                     QHostAddress(ui->serverIp->text()),
                                     ui->serverPort->text().toInt());
            ui->sendBuffer->clear();
        }
    });
    /* receive msg from client socket */
    connect(this->udp, &QUdpSocket::readyRead, this, [=](){
        /* get receive data length */
        qint64 len = this->udp->pendingDatagramSize();
        /* new space and length is len */
        QByteArray array(len, 0);
        /* receive data */
        this->udp->readDatagram(array.data(), len);
        /* show in recvBuffer */
        ui->recvBuffer->append(array);
    });

}

Client::~Client()
{
    delete ui;
}
